<?php

/**
 * Created by zw.
 * User: Administrator
 * Date: 14-8-19
 * Time: 上午10:56
 */

namespace Admin\Controller;

use Think\Controller;
use Think\Model;

class ModelController extends Controller {

    public function index() {
        $m = M('model');
        $rsArr = $m->select();

        $this->assign('rsArr', $rsArr);
        $this->display();
    }

    //更改模型状态
    function setstatus($mid, $isshow) {
        $m = M('model');
        $data['isshow'] = $isshow;
        if ($m->where("id=$mid")->save($data)) {
            if ($isshow == 0) {
                $this->success("禁用成功");
            } else {
                $this->success("启用成功");
            }
        };
    }

    //新增模型
    function add() {
        $m = D('model');
        if (IS_POST) {
            $issystem = isset($_POST['issystem']) ? $_POST['issystem'] : 1;
            if ($issystem == 1) {
                $addtable = 'add' . trim($_POST['nid']);
            } else {
                $addtable = trim($_POST['nid']);
            }
            if ($issystem == 1) {
                $tabsql = "CREATE TABLE `" . C('DB_PREFIX') . $addtable . "`(
					`aid` int(11) NOT NULL default '0'";
                $tabsql .= " PRIMARY KEY ) ENGINE=InnoDB DEFAULT CHARSET=" . C('DB_CHARSET') . "; ";
            } else {
                $tabsql = "CREATE TABLE `" . C('DB_PREFIX') . $addtable . "`(
					`id` int(11) NOT NULL";
                $tabsql .= " PRIMARY KEY ) ENGINE=InnoDB DEFAULT CHARSET=" . C('DB_CHARSET') . "; ";
            }
            $m2 = new Model();
            if ($m2->execute($tabsql) !== false) {
                $data = $_POST;
                $data['addtable'] = $addtable;
                if ($m->create($data)) {
                    if ($m->add()) {
                        $this->success('添加模型成功');
                    } else {
                        $this->error('添加模型失败');
                    }
                }
            }
        } else {
            $this->display();
        }
    }

    //修改模型
    function edit() {
        $m = D('model');
        if (IS_POST) {
            if ($m->create()) {
                if ($m->save()) {
                    $this->success('模型修改成功');
                } else {
                    $this->error('模型修改失败');
                }
            }
        } else {
            $mid = isset($_GET['mid']) ? $_GET['mid'] : null;
            $rsArr = $m->where("id=$mid")->find();
            $this->assign("rsArr", $rsArr);
            $this->assign('mid', $mid);
            $this->display();
        }
    }

    //删除模型
    function del() {
        $m = M('model');
        $mid = isset($_GET['id']) ? $_GET['id'] : null;
        if ($mid == null) {
            $this->error('对不起,您删除的模型不存在');
        } else {
            $addtable = $m->where("id=$mid")->getField('addtable');
            $m2 = new Model();
            $tablesql = 'DROP TABLE ' . C('DB_PREFIX') . $addtable;
            if ($m2->execute($tablesql) !== false) {
                if ($m->where("id=$mid")->delete()) {
                    $this->success('删除模型成功');
                } else {
                    $this->error('删除模型失败');
                }
            } else {
                $this->error('删除模型失败');
            }
        }
    }

    //新增字段
    function fieldadd() {
        $m = M('model');
        if (IS_POST) {
            $mid = $_POST['id'];
            $ftips = isset($_POST['ftips']) ? $_POST['ftips'] : '';
            $fname = isset($_POST['fname']) ? $_POST['fname'] : '';
            $fname = trim($fname);
            $ftype = isset($_POST['ftype']) ? $_POST['ftype'] : 'varchar';
            $fdefault = isset($_POST['fdefault']) ? $_POST['fdefault'] : '';
            $fdefault = trim($fdefault);
            $fsize = isset($_POST['fsize']) ? $_POST['fsize'] : 250;
            $fsize = ($fsize) < 250 ? $fsize : 250;
            $fmust = isset($_POST['fmust']) ? $_POST['fmust'] : '0';
            $fdisplay = isset($_POST['fdisplay']) ? $_POST['fdisplay'] : '0';

            $arr = $m->field('fieldset,type,nid,issystem')->where("id='$mid'")->find();
            if ($arr['issystem'] == 2)
                $addtable = C('DB_PREFIX') . $arr['nid'];
            else
                $addtable = C('DB_PREFIX') . 'add' . $arr['nid'];


            if (preg_match("#^(select|radio|checkbox)$#i", $ftype)) {
                if (!preg_match("#,#", $fdefault) && !preg_match("#^__.*__$#i", $fdefault)) {
                    $this->error("你设定了字段为 {$ftype} 类型，必须在默认值中指定元素列表，如：'a,b,c' ");
                    return;
                }
            }

            $fieldinfos = GetFieldMake($ftype, $fname, $fdefault, $fsize);
            $ntabsql = $fieldinfos[0];
            $buideType = $fieldinfos[1];
            $tablesql = " ALTER TABLE `$addtable` ADD  $ntabsql ";

      

            $m2 = new Model();
            if ($m2->execute($tablesql) !== false) {

                if (empty($arr['fieldset'])) {
                    $fields[0]['name'] = $fname;
                    $fields[0]['type'] = $ftype;
                    $fields[0]['default'] = $fdefault;
                    $fields[0]['size'] = $fsize;
                    $fields[0]['intro'] = $ftips;
                    $fields[0]['must'] = $fmust;
                    $fields[0]['display'] = $fdisplay;
                } else {
                    $fields = unserialize($arr['fieldset']);
                    $temp['name'] = $fname;
                    $temp['type'] = $ftype;
                    $temp['default'] = $fdefault;
                    $temp['size'] = $fsize;
                    $temp['intro'] = $ftips;
                    $temp['must'] = $fmust;
                    $temp['display'] = $fdisplay;
                    $fields[] = $temp;
                }

                $field_str = serialize($fields);
                $data['id'] = $mid;
                $data['fieldset'] = $field_str;


                $m->create($data);

                if ($m->save()) {
                    $this->success("添加字段成功！");
                } else {
                    $this->error("添加字段失败！");
                }
            } else {
                $this->error("添加字段失败！");
            }
        } else {
            $mid = isset($_GET['mid']) ? $_GET['mid'] : 0;
            if ($mid != 0) {
                $this->assign('mid', $mid);
                $this->display();
            }
        }
    }

    //查看字段
    function fieldlist($mid) {
        $mid = isset($_GET['mid']) ? $_GET['mid'] : null;
        if ($mid == null) {
            $this->error('读取模型出错！');
        }
        $m = D('model');
        $arr = $m->field('nid,fieldset,addtable,name')->where('id=' . $mid)->find();
        $table = $arr['addtable'];
        $arr2 = unserialize($arr['fieldset']);
        $flist = "";
        foreach ($arr2 as $k => $v) {
            $flist.="<li class='ui-state-default' _index='" . $k . "' > " . $v['name'] . " <span class='controls'><a href='" . U('model/fielddel') . "?mid=" . $mid . "&field=" . $v['name'] . "'>删除</a>&nbsp;&nbsp;<a href='" . U('model/fieldedit') . "?mid=" . $mid . "&field=" . $v['name'] . "'>修改</a></span></li>";
        }
 
        $this->assign('arr2',$arr2);
        $this->assign('flist', $flist);
        $this->assign('mid', $mid);
        $this->display();
    }

    //修改字段
    function fieldedit() {
        $m = D('model');
        if (IS_POST) {
            $mid = isset($_POST['id']) ? $_POST['id'] : null;
            if ($mid == null) {
                $this->error("读取字段错误！");
                return;
            }

            $ftips = isset($_POST['ftips']) ? $_POST['ftips'] : '';
            $fname = isset($_POST['fname']) ? $_POST['fname'] : null;
            $ftype = isset($_POST['ftype']) ? $_POST['ftype'] : 'varchar';
            $fdefault = isset($_POST['fdefault']) ? $_POST['fdefault'] : '';
            $fdefault = trim($fdefault);
            $fsize = isset($_POST['fsize']) ? $_POST['fsize'] : 250;
            $fsize = ($fsize < 250) ? $fsize : 250;
            $fmust = isset($_POST['fmust']) ? $_POST['fmust'] : '0';
            $fdisplay = isset($_POST['fdisplay']) ? $_POST['fdisplay'] : '0';

            $arr = $m->field('fieldset,type,nid,issystem')->where("id='$mid'")->find();
            if ($arr['issystem'] == 2)
                $addtable = C('DB_PREFIX') . $arr['nid'];
            else
                $addtable = C('DB_PREFIX') . 'add' . $arr['nid'];

            if (preg_match("#^(select|radio|checkbox)$#i", $ftype)) {
                if (!preg_match("#,#", $fdefault) && !preg_match("#^__.*__$#i", $fdefault)) {
                    $this->error("你设定了字段为 {$ftype} 类型，必须在默认值中指定元素列表，如：'a,b,c'");
                    return;
                }
            }

            $fieldinfos = GetFieldMake($ftype, $fname, $fdefault, $fsize);
            $ntabsql = $fieldinfos[0];
            $tablesql = "ALTER TABLE `$addtable` CHANGE `$fname` " . $ntabsql;

            $m2 = new Model();
            if ($m2->execute($tablesql) !== false) {
                $ofield = unserialize($arr['fieldset']);
                foreach ($ofield as $k => $v) {
                    if ($v['name'] == $fname) {
                        $ofield[$k]['type'] = $ftype;
                        $ofield[$k]['default'] = $fdefault;
                        $ofield[$k]['size'] = $fsize;
                        $ofield[$k]['intro'] = $ftips;
                        $ofield[$k]['must'] = $fmust;
                        $ofield[$k]['display'] = $fdisplay;
                        break;
                    }
                }

                $field_str = serialize($ofield);
                $data['id'] = $mid;
                $data['fieldset'] = $field_str;
                $m->create($data);
                if ($m->save() !== false) {
                    $this->success("更新字段成功！", "fieldlist?mid=$mid");
                } else {
                    $this->error("该字段没有更新任何内容！");
                }
            } else {
                $this->error("更新字段结构失败！");
            }
        } else {
            $mid = isset($_GET['mid']) ? $_GET['mid'] : null;
            $field = isset($_GET['field']) ? $_GET['field'] : null;
            $arr = $m->field('nid,fieldset,addtable')->where('id=' . $mid)->find();

            $ofield = unserialize($arr['fieldset']);
            foreach ($ofield as $k => $v) {
                if ($v['name'] == $field) {
                    $ofield = $ofield[$k];
                    break;
                }
            }
            $this->assign('mid', $mid);
            $this->assign('ofield', $ofield);
            $this->display();
        }
    }

    //删除字段
    function fielddel() {
        $m = D('model');
        $mid = isset($_GET['mid']) ? $_GET['mid'] : null;
        $field = isset($_GET['field']) ? $_GET['field'] : null;
        if ($mid == null || $field == nul) {
            $this->error("读取字段错误！");
            return;
        }

        $arr = $m->field('nid,fieldset,addtable')->where('id=' . $mid)->find();
        if ($field == 'id' || $field == 'aid') {
            $this->error("系统模型不能删除！");
            return;
        }
        $table = C('DB_PREFIX') . $arr['addtable'];
        $tablesql = "ALTER TABLE `$table` DROP `$field` ";
        $m2 = M();
        if ($m2->execute($tablesql) !== false) {

            $ofield = unserialize($arr['fieldset']);
            foreach ($ofield as $k => $v) {
                if ($v['name'] == $field) {
                    unset($ofield[$k]);
                    //$ofield[$k] = null;
                    break;
                }
            }
            $field_str = serialize($ofield);
            $data['id'] = $mid;
            $data['fieldset'] = $field_str;
            $m->create($data);
            if ($m->save()) {
                $this->success("删除字段成功！");
            } else {
                $this->error("删除字段失败！");
            }
        } else {
            $this->error("删除字段结构失败！");
        }
    }

}